<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */

class UserIdentity extends CUserIdentity
{
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */

    protected $error;

	public function login()
	{
        if(!$this->username || !$this->password){
            $this->addError(Yii::t('account/customer', 'errorCanNotLogin'));
            return false;
        }

        $result=Yii::app()->user->loginUser($this);
        if(!$result) $this->addError(Yii::app()->user->message);
        return $result;
	}

    public function register($data=array())
    {
        try{
            $customer=Yii::app()->user->model;
            $customer->attributes=$data;
            $customer->save();

            if($customer->errors) $this->addError($customer->errors);
            else{
                $this->username=$customer->email;
                $this->password=$data['password'];
                return Yii::app()->user->loginUser($this);
            }
        }catch(Exception $e){
            $this->addError($e->getCode());
        }

        if(!$this->error) return true;
        else return false;
    }

    public function getError()
    {
        return $this->error;
    }

    protected function addError($error='')
    {
        if(!$error) return;
        if(is_array($error)){
            foreach($error as $message){
                $this->error.=$message.'; /n';
            }
        }else
            $this->error.=$error.'; /n';
    }
}